import Taro, { getStorageSync } from '@tarojs/taro'
import { AtMessage } from 'taro-ui'
import styles from './index.module.scss'

export interface OrderDetail {
  content: string
  count: number
  createTime: string
  description: string
  id: number
  imgs: string[]
  note: string
  payMethod: string
  payTime: string
  price: number
  productCover: string
  productId: number
  productName: string
  receiverAddress: string
  receiverName: string
  receiverPhone: string
  status: number
  unit: string
  updateTime: string
  userId: number
  weight: number
  [property: string]: any
}

const Order = ({ orderInfo, onUpdate }) => {
  const handleEnterOrderDetailPage = () => {
    Taro.navigateTo({
      url: `/moduleA/pages/orderDetail/index?id=${orderInfo.id}`,
    })
  }

  const handleDeleteOrder = async (event) => {
    event.stopPropagation()
    try {
      const res = await Taro.request({
        url: `${process.env.TARO_APP_API}/order/api/v1/order/deleteById?orderId=${orderInfo?.id}&goodsId=${orderInfo?.productId}`, //仅为示例，并非真实的接口地址
        method: 'DELETE',
        header: {
          'content-type': 'application/json', // 默认值
          token: getStorageSync('token'),
        },
      })
      console.log('删除', res)
      if (res && res.code === 0) {
        Taro.showToast({
          title: '订单删除成功',
          icon: 'success',
        })
      } else {
        const errorMsg = res && res.msg ? res.msg : 'Unknown error'
        Taro.showToast({
          title: errorMsg,
          icon: 'error',
        })
      }
    } catch (error) {
      console.log('出现错误')
    }

    onUpdate()
  }

  const handlePayOrder = (event) => {
    event.stopPropagation()
    Taro.navigateTo({
      url: `/pages/pay/index?id=${orderInfo.id}`,
    })
  }

  const handleCancelOrder = async (event) => {
    event.stopPropagation()
    try {
      const res = await Taro.request({
        url: `${process.env.TARO_APP_API}/order/api/v1/order/cancel?orderId=${orderInfo?.id}&goodsId=${orderInfo?.productId}`,
        method: 'PUT',
        header: {
          'content-type': 'application/json', // 默认值
          token: getStorageSync('token'),
        },
      })
      if (res && res.code === 0) {
        Taro.showToast({
          title: '订单取消成功',
          icon: 'success',
        })
      } else {
        const errorMsg = res && res.msg ? res.msg : 'Unknown error'
        Taro.showToast({
          title: errorMsg,
          icon: 'error',
        })
      }
    } catch (error) {
      console.log('出现错误')
    }

    onUpdate()
  }

  return (
    <>
      <div className={styles.orderItem} onClick={handleEnterOrderDetailPage}>
        <div className={styles.orderTop}>
          <div className={styles.orderId}>{orderInfo.id}</div>
          <div className={styles.orderStatus}>
            {orderInfo.status === 0
              ? '待支付'
              : orderInfo.status === 1
                ? '已取消'
                : '已支付'}
          </div>
        </div>
        <div className={styles.orderContent}>
          <div className={styles.orderContentLeft}>
            <img className={styles.img} src={orderInfo.productCover} alt='' />
          </div>
          <div className={styles.orderContentRight}>
            <div className={styles.goodsDesc}>{orderInfo.productName}</div>
            <div className={styles.goodsNum}>x{orderInfo.count}</div>
            <div className={styles.goodsPrice}>
              实付：¥{orderInfo.price.toFixed(2)}
            </div>
          </div>
        </div>
        {/* {orderInfo.status == 0 && ( */}
        <div className={styles.orderFooter}>
          {(orderInfo.status === 1 || orderInfo.status === 2) && (
            <div className={styles.deleteBtn} onClick={handleDeleteOrder}>
              删除订单
            </div>
          )}
          {orderInfo.status === 0 && (
            <>
              <div className={styles.cancelBtn} onClick={handleCancelOrder}>
                取消订单
              </div>
              <div className={styles.payBtn} onClick={handlePayOrder}>
                去支付
              </div>
            </>
          )}
        </div>
        {/* )} */}
      </div>
      <AtMessage />
    </>
  )
}

export default Order
